#pragma once

#include <iostream>
#include <string>
#include <error.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

using namespace std;

#define Mode 0666
#define Path "./fifo"

class Fifo
{
public:
    // 构造时创建命名管道
    Fifo(const string path = Path)
        : _path(path)
    {

        int n = mkfifo(_path.c_str(), Mode);
        if (n < 0)
        {
            printf("create fifo fail, errno is %d, errinfo is %s\n", errno, strerror(errno));
        }
        else
        {
            printf("create fifo successfully\n");
        }
    }

    // 删除管道文件
    ~Fifo()
    {
        unlink(_path.c_str());
        printf("destroy fifo successfully\n");
    }

private:
    string _path;
};

class Sync
{
public:
    Sync(const char* Pathname = Path)
        :pathname(Pathname)
    {}

        // 已只读方式打开命名管道
    int OpenRD()
    {
        int fd = open(pathname, O_RDONLY);
        if (fd < 0)
        {
            printf("open fifo fail, errno is %d, errinfo is %s\n", errno, strerror(errno));
            return -1;
        }
        return fd;
    }

    // 已只写方式打开命名管道
    int OpenWR()
    {
        int fd = open(pathname, O_WRONLY);
        if (fd < 0)
        {
            printf("open fifo fail, errno is %d, errinfo is %s\n", errno, strerror(errno));
            return -1;
        }
        return fd;
    }

    // 当服务器还没读完时，让客户端写等待
    bool Wait(int fd)
    {
        bool ret = true;
        uint32_t c = 0;
        ssize_t n = read(fd, &c, sizeof(uint32_t));
        if (n == 0)
        {
            ret = false;
        }
        else if (n < 0)
        {
            printf("read fail, errno is %d, errinfo is %s\n", errno, strerror(errno));
            return false;
        }
        return ret;
    }

    // 服务器读完时，唤醒客户端写
    void WakeUp(int fd)
    {
        uint32_t c = 0;
        ssize_t n = write(fd, &c, sizeof(uint32_t));
        if (n < 0)
        {
            printf("write fail, errno is %d, errinfo is %s\n", errno, strerror(errno));
            return;
        }
    }

    // 关闭命名管道
    void Close(int fd)
    {
        close(fd);
    }

private:
    const char* pathname;
};